<template>
  <div class="attr">
    <!-- 分类 scene控制子组件select disable -->
    <Category :scene="scene"/>
    <!-- 表格 -->
    <el-card style="margin: 10px 0;">

      <!-- 属性表格 -->
      <template v-if="scene == 0">
        <el-button @click="addAttr" :disabled="!categoryStore.c3Id" type="primary" icon="Plus">添加平台属性</el-button>
        <el-table :data="attrArr" border style="margin: 10px 0;">
          <el-table-column align="center" width="80px" label="序号" type="index"></el-table-column>
          <el-table-column width="150" label="属性名称" prop="attrName"></el-table-column>
          <el-table-column label="属性值名称">
            <template #default="{row}">
              <el-tag style="margin: 5px" v-for="item in row.attrValueList" :key="item.id">{{ item.valueName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column width="150" label="操作">
            <template #default="{row}">
              <el-button type="warning" size="small" icon="Edit" @click="updateAttr(row)"></el-button>
              <el-popconfirm width="200" @confirm="deleteAttr(row.id)" :title="`确定删除${row.attrName}吗?`">
                <template #reference>
                  <el-button type="danger" size="small" icon="Delete"></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </template>

      <!-- 添加或修改属性表格 -->
      <template v-else>
        <el-form inline>
          <el-form-item label="属性名称">
            <el-input v-model="attrParams.attrName" placeholder="请输入属性名称"></el-input>
          </el-form-item>
        </el-form>
        <el-button @click="addAttrValue" :disabled="!attrParams.attrName" type="primary" icon="Plus">添加属性值</el-button>
        <el-button type="default"  @click="cancel">取消</el-button>

        <!-- 表格 -->
        <el-table :data="attrParams.attrValueList" border style="margin: 10px 0">
          <el-table-column label="序号" type="index" align="center" width="80"></el-table-column>
          <el-table-column label="属性值名称" >
            <template #default="{row, $index}"> 
              <!-- row为当前的属性值对象 -->
              <!-- <el-input :ref="(vc:any) => inputArr[$index] = vc" @blur="toLook(row,$index)" v-if="row.flag" v-model="row.valueName" placeholder="请输入属性值"></el-input> -->
              <el-input :ref="(el) => handler(el, row, $index)" @blur="toLook(row,$index)" v-if="row.flag" v-model="row.valueName" placeholder="请输入属性值"></el-input>
              <div @click="toEdit(row, $index)" v-else>{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{$Index}">
              <el-button type="danger" size="small" icon="Delete" @click="attrParams.attrValueList.splice($Index, 1)"></el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 保存取消 -->
        <el-button :disabled="attrParams.attrValueList.length <= 0" type="primary" @click="save">保存</el-button>
        <el-button type="default" @click="cancel">取消</el-button>
      </template>

    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, reactive, nextTick, onBeforeUnmount } from  'vue'
import { reqAttr, reqAddOrUpdateAttr, reqRemoveAttr } from '@/api/product/attr'
import type { AttrList, Attr, AttrValue } from '@/api/product/attr/type'
import { useCategoryStore } from '@/store/modules/category'
import { ElMessage } from 'element-plus'
const categoryStore = useCategoryStore()
// 定义新增或修改属性的数据
const attrParams = reactive<Attr>({
  attrName:'', //属性名称
  categoryId: '',//三级分类Id
  categoryLevel: '',//分类的分级
  attrValueList: [] //属性的属性值数组
})
// 存储el-input ref的数组
const inputArr = ref<any>([])
// 根据三级分类id 获取属性数组
watch(()=>categoryStore.c3Id, ()=>{
  // 清空上次查询到的数据
  attrArr.value = []
  // 保证三级分类id存在
  if(!categoryStore.c3Id) return
  getAttr()
})

// 获取属性方法
const attrArr = ref<AttrList>([])
const getAttr = async () => {
  // 获取分类id
  const { c1Id, c2Id, c3Id } = categoryStore
  const res = await reqAttr(c1Id, c2Id, c3Id)
  if(res.code == 200) {
    attrArr.value = res.data
  }
}

// 控制卡片内表格的切换 
const scene = ref(0)

// 添加属性按钮回调 
const addAttr = () => {
  // 修改赋值时 会有id一起赋给attrParams 要删除
  if(attrParams.id) {
    delete attrParams.id
  }
  // 先清空数据
  Object.assign(attrParams, {
    attrName:'',
    categoryId: '',
    categoryLevel: 3,
    attrValueList: [] 
  })
  scene.value = 1
}

// 修改属性按钮
const updateAttr = (row: Attr) => {
  scene.value = 1
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)))
}

// 取消按钮回调
const cancel = () => {
  scene.value = 0
}

// 添加属性值按钮回调
const addAttrValue = () => {
  
  //向attrParams中的attrValueList添加一个属性值对象
  attrParams.attrValueList.push({
    valueName: '',
    flag: true // 控制每个属性值input和div切换
  })
  nextTick(()=>{
    // 获取最后的Input聚焦
    inputArr.value[inputArr.value.length-1].focus()
  })
}

// 查看切换
const toLook = (row: AttrValue, index: number) => {
  // 要保证valueName有值才能blur
  if(row.valueName.trim() == '') {
    // 删除属性值数组中的空的
    attrParams.attrValueList.splice(index, 1)
    return ElMessage({
      type: 'error',
      message: '不能添加空的属性值'
    })
  }

  // 非法情况2 有重复地属性 
  // 用除自己以外的item和其他item比较
  const repeat = attrParams.attrValueList.find(item => {
    if(item != row) {
      // 说明不是当前项
      return item.valueName == row.valueName
    }
  })
  if(repeat) {
    // 删除重复的属性值
    attrParams.attrValueList.splice(index, 1)
    return ElMessage({
      type: 'error',
      message: '不能添加重复的属性值'
    })
  }
  row.flag = false
}

// 编辑模式
const toEdit = (row: AttrValue, index:number) => {
  // 关闭其他所有flag
  attrParams.attrValueList.forEach(item => item.flag = false)
  row.flag = true
  nextTick(()=>{
    // 当前获取焦点
    inputArr.value[index].focus()
  })
  
}

// ref绑定方法 每次input和div发生切换 都会触发, 并返回当前的element
const handler = (el:any,row:any, $index:number) => {
  // 当input模板结构或内容发生变化就会触发
  // 可以获取当前input的组件实例
  // console.log(el)
  inputArr.value[$index] = el
}



// 删除属性
const deleteAttr = async (id:number) => {
  const res = await reqRemoveAttr(id)
  if(res.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功~'
    })
    getAttr()
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败~'
    })
  }
}
// 路由跳转 清空
onBeforeUnmount(()=>{
  // 重置仓库数据
  categoryStore.$reset()
})

//保存按钮回调
const save = async () => {
  attrParams.categoryId = categoryStore.c3Id
  attrParams.categoryLevel = 3
  const res = await reqAddOrUpdateAttr(attrParams)
  if(res.code == 200) {
    scene.value = 0
    ElMessage({
      type: 'success',
      message: attrParams.id?'修改成功~':'添加成功~'
    })
    getAttr()
  } else {
    ElMessage({
      type: 'error',
      message: attrParams.id?'修改失败~':'添加失败~'
    })
  }
}

</script>

<style lang="scss">


</style>
